package com.hmy.pig.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.UnknownHostException;

/**
 * @author yyh
 * @date 2024/2/22 11:21
 * @description TencentCOS
 */
@Component
public class TencentCOS {
    private String secretId = "AKIDqdKq7B0c1HH4dyCCzYsxoS7YllY5OSI4";
    private String secretKey = "f5IJ7g094kBPXR8brwpZAbnlU2OZYO1Q";
    private String region = "ap-nanjing";
    private String bucketName = "yyh24537-1322270908";
    private String path = "https://yyh24537-1322270908.cos.ap-nanjing.myqcloud.com";

    public COSClient initCOSClient(){
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    /**
     * 上传文件
     */
    public  String upLoad(InputStream is, String filename) throws CosClientException {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("image/*");
            // 指定要上传到 COS 上对象键
            String key = getFileKey(filename);

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, is,metadata);
            COSClient cosClient1 = initCOSClient();
            cosClient1.putObject(putObjectRequest);
            // 设置权限(公开读)
            cosClient1.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            return path + "/"+ key;
        } catch (Exception serverException) {
            serverException.printStackTrace();
        }
        return "";
    }

    /**
     * 生成文件路径
     *
     * @return
     */
    private String getFileKey(String code) {
        String filePath = "test/";
        filePath += code + ".jpg";
        return filePath;
    }
}
